package Tire;

import javax.swing.tree.TreeNode;

public class TireTree {
    public static class TireNode{
        public int pass;//以该字符作为前缀出现过几次
        public int end;//最后在结尾出现过几次
        public TireNode[] nexts;
        public TireNode(){
            pass=0;
            end=0;
            //nexts[0] == null 代表没有走向'a'的路径
            nexts=new TireNode[26];//如果字符特别多,HashMap<char,Node>nexts;
        }
    }

    public static class Trie{
        private TireNode root;
        public Trie(){
            root=new TireNode();
        }
        public void insert(String word){
            if (word == null){
                return;
            }
            char[] chars=word.toCharArray();
            TireNode node=root;//从根节点出发
            node.pass++;
            int index=0;
            for (int i = 0; i < chars.length; i++) {
                index=chars[i]-'a';
                if (node.nexts[index] == null){
                    node.nexts[index] =new TireNode();
                }
                node = node.nexts[index];
                node.pass++;
            }
            node.end++;
        }
        //查找word出现过几次
        public int search(String word){
            if (word == null)return 0;
            char[] chars = word.toCharArray();
            TireNode node = root;
            int index = 0 ;
            for (int i=0; i < chars.length ;i++){
                index = chars[i]-'a';
                if (node.nexts[index] == null){
                    /*代表字符没走完,但是没路了,说明没加入过*/
                    return 0;
                }
                node = node.nexts[index];
            }
            return node.end;
        }
        //所有加入的字符串中,有几个是以pre前缀的
        public int prefinNumber(String pre){
            if (pre == null)return 0;
            char[] chars=pre.toCharArray();
            TireNode node = root;
            int index=0;
            for (int i = 0; i < chars.length; i++) {
                index = chars[i]-'a';
                if (node.nexts[index] == null){
                    return 0;
                }
                node=node.nexts[index];
            }
            return node.pass;
        }

        /*删除一个字符串
        * 删除沿途pass值和最后的end值*/
        public void delete(String word){
            if (search(word) != 0){
                //先做检查,是否存在
                char[] chars=word.toCharArray();
                TireNode node=root;
                node.pass--;
                int index=0;
                for (int i = 0; i < chars.length; i++) {
                    if (--node.nexts[index].pass ==0){
                        /*说明该字符删除完了*/
                        node.nexts[index] =null;
                        //只有Java能直接return ,因为Java有垃圾回收机制
                        return;
                    }
                    node = node.nexts[index];
                }
                node.end--;
            }
        }

    }

}
